package com.koron.common.core.formatter;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;
import java.util.Locale;

/**
 * @author jzp
 * @since 2021/7/14 14:52
 */
@Component
public class DateFormatter implements Formatter<Date> {
    /**
     * pattern
     */
    public static final String TIME_PATTERN = "HH:mm:ss";
    public static final String DATE_NO_DD_PATTERN = "yyyy-MM";
    public static final String DATE_PATTERN = "yyyy-MM-dd";
    public static final String DATE_EXCEL_PATTERN = "yyyy/MM/dd";
    public static final String DATE_TIME_NO_SS_PATTERN = "yyyy-MM-dd HH:mm";
    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_TIME_EXCEL_PATTERN = "yyyy/MM/dd HH:mm:ss";

    /**
     * patterns
     */
    public static final String[] DATE_PATTERNS = {TIME_PATTERN, DATE_NO_DD_PATTERN, DATE_PATTERN, DATE_TIME_NO_SS_PATTERN, DATE_TIME_PATTERN};

    @Override
    public Date parse(String s, Locale locale) throws ParseException {
        return DateUtils.parseDate(s.trim(), DATE_PATTERNS);
    }

    @Override
    public String print(Date date, Locale locale) {
        return DateFormatUtils.format(date, DATE_TIME_PATTERN);
    }
}
